package cn.pli.bike.model.http;

import com.google.gson.Gson;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by kangjie on 2017/11/17.
 */

public class ResponseCacheConvertFactory extends Converter.Factory{

    /**
     * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    public static ResponseCacheConvertFactory create(String key) {
        return create(new Gson(),key);
    }

    /**
     * Create an instance using {@code gson} for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    public static ResponseCacheConvertFactory create(Gson gson,String key) {
        return new ResponseCacheConvertFactory(gson, key);
    }

    private final Gson gson;
    private String key;

    private ResponseCacheConvertFactory(Gson gson,String key) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
        this.key = key;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        return new CacheResponseBodyConverter<>(gson,type, key);
    }

}